<?php
/*********************************************************************\
* This File is a part of BH-PANEL (Breizh-Heberg Panel v2.1)
* Copyright (C) 2008-2009 the BH Developpers : Vincent Giersch <mail@vincordi.fr>, Cyprien Laleau <fanning.fr@gmail.com> and Edwin Cabiten <marmottes44@hotmail.fr>
* See file AUTHORS to get more informations

* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.

* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.

* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
/*********************************************************************/


define('CONFIG_ROOT', '/etc/bh/');
define('CODE_ROOT', '/opt/hosting/daemons/includes/');
define('CURRENT_SERVER', 4);
define('PARTITION', '/');
define('APACHE_CONF', CONFIG_ROOT.'serveurs/data_apache/_apache2.conf');
define('TMP_PASS', 'KaflPmKVygEV65L');
include CODE_ROOT."common.php";
//////////////////////////////////////////////////////
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=utf-8\n";
$headers .= "From: Breizh Héberg Bot <robot@breizh-heberg.net>\n";
$headers .= "Reply-To: Support Breizh-Héberg <support@breizh-heberg.net>\n";
//////////////////////////////////////////////////////
$test_write = query("SELECT COUNT(*) FROM comptes_heberg  WHERE etat = '1' AND serveur_apache = '3'");
if(mysql_num_rows($test_write) < "1") {
echo "FAILED :".mysql_num_rows($test_write)."\n";
 exit();
}
echo "RUN... :". mysql_num_rows($test_write)."\n";
//////////////////////////////////////////////////////
@unlink(APACHE_CONF);
$_a2c = fopen(APACHE_CONF, "a+");

// --------------------------- Comptes  d'Hébergement
$liste_ = query("SELECT 
				comptes_heberg.*,
				UNIX_TIMESTAMP(comptes_heberg.expire)
				FROM comptes_heberg
				WHERE etat = '1' AND serveur_apache = '".CURRENT_SERVER."'");
While($liste = mysql_fetch_array($liste_)) {
	@shell_exec("sudo mkdir /home/".$liste['user_linux']."/logs/ && chmod 777 /home/".$liste['user_linux']."/logs/");
	// Alias Default : .breizh-web.net
	if(!file_exists(CONFIG_ROOT."serveurs/data_apache/breizh-web.net/".$liste['user_linux'].".conf")) {
		$vhost = array();
		$vhost['{root_log}'] = CONFIG_ROOT."serveurs/logs_apache";
		$vhost['{user}'] = $liste['user_linux'];	
		$final = str_replace(array_keys($vhost), array_values($vhost), file_get_contents(CONFIG_ROOT."tpl/apache-vhost-bwnet.html"));
		$save_vh = file_put_contents(CONFIG_ROOT."serveurs/data_apache/breizh-web.net/".$liste['user_linux'].".conf", $final);
	}
	fputs($_a2c, "Include ".CONFIG_ROOT."serveurs/data_apache/breizh-web.net/".$liste['user_linux'].".conf"."\n");
	// Autres alias et domaines du client
	$_client_alias = query("SELECT * FROM hebergdata_doms WHERE id_heberg = '".$liste['id']."'");
	While($client_alias = mysql_fetch_array($_client_alias)) {
		if($client_alias['id_alias_bh'] != 0) {
			//Alias BH
			if(!file_exists(CONFIG_ROOT."serveurs/data_apache/".$alias_bh[$client_alias['id_alias_bh']]."/".$liste['user_linux']."-".$client_aliad['domaine'].".conf")) {
				$vhost = array();
				$vhost['{user}'] = $liste['user_linux'];	
				$vhost['{directory}'] = $client_alias['dossier'];
				$vhost['{domaine}'] = $client_alias['domaine'];
				$vhost['{root_log}'] = CONFIG_ROOT."serveurs/logs_apache";
				$vhost['{alias_bh}'] = $alias_bh[$client_alias['id_alias_bh']];
				$final = str_replace(array_keys($vhost), array_values($vhost), file_get_contents(CONFIG_ROOT."tpl/apache-vhost-aliasbh.html"));
				$save_vh = file_put_contents(CONFIG_ROOT."serveurs/data_apache/".$alias_bh[$client_alias['id_alias_bh']]."/".$liste['user_linux']."-".$client_alias['domaine'].".conf", $final);
			}
			fputs($_a2c, "Include ".CONFIG_ROOT."serveurs/data_apache/".$alias_bh[$client_alias['id_alias_bh']]."/".$liste['user_linux']."-".$client_alias['domaine'].".conf"."\n");
		}
		else {
			if(!file_exists(CONFIG_ROOT."serveurs/data_apache/".$client_alias['domaine'].".conf") OR $client_alias['etat'] == 6) {
				$vhost = array();
				$vhost['{user}'] = $liste['user_linux'];	
				$vhost['{directory}'] = $client_alias['dossier'];
				$vhost['{root_log}'] = CONFIG_ROOT."serveurs/logs_apache";
				$vhost['{domaine}'] = $client_alias['domaine'];
				$final = str_replace(array_keys($vhost), array_values($vhost), file_get_contents(CONFIG_ROOT."tpl/apache-vhost-doms.html"));
				$save_vh = file_put_contents(CONFIG_ROOT."serveurs/data_apache/".$liste['user_linux']."-".$client_alias['domaine'].".conf", $final);
				query("UPDATE hebergdata_doms SET etat = 1 WHERE domaine = '".$client_alias['domaine']."'");
			}		
			fputs($_a2c, "Include ".CONFIG_ROOT."serveurs/data_apache/".$liste['user_linux']."-".$client_alias['domaine'].".conf"."\n");

			$_ssdoms = query("SELECT * FROM hebergdata_ssdoms WHERE id_dom = '".$client_alias['id']."'");
			While($ss_doms = mysql_fetch_array($_ssdoms)) {
				if(!file_exists(CONFIG_ROOT."serveurs/data_apache/".$liste['user_linux']."-".$client_alias['domaine']."-".$ss_doms['id'].".conf") OR $client_alias['etat'] == 3) {
					$vhost = array();
					$vhost['{user}'] = $liste['user_linux'];	
					$vhost['{directory}'] = $ss_doms['dossier'];
					$vhost['{root_log}'] = CONFIG_ROOT."serveurs/logs_apache";
					$vhost['{domaine}'] = $ss_doms['ss_dom'].".".$client_alias['domaine'];
					$final = str_replace(array_keys($vhost), array_values($vhost), file_get_contents(CONFIG_ROOT."tpl/apache-vhost-doms.html"));
					$save_vh = file_put_contents(CONFIG_ROOT."serveurs/data_apache/".$liste['user_linux']."-".$client_alias['domaine']."-".$ss_doms['id'].".conf", $final);
				}
				fputs($_a2c, "Include ".CONFIG_ROOT."serveurs/data_apache/".$liste['user_linux']."-".$client_alias['domaine']."-".$ss_doms['id'].".conf"."\n");
			}	
		}
	}
}
fclose($_a2c);
	
	// ---------------------------------------------------------------------------------------------
	//  Création des comptes - 2nd partie - Création des répertoires + vhosts
	// HEBERGEMENT / NOUVELLES COMMANDES
	echo 'ok';
	$liste_commandes_ = query("SELECT 
									commandes_data.id AS co_id, 
									commandes_data.id_produit,
									commandes_data.type_produit,
									commandes_data.type_commande,
									commandes_data.domaine_or_user_linux,
									commandes_data.commande_etat,
									commandes_data.server_apache,
									comptes_heberg.id AS ch_id,
									comptes_heberg.u_nic,
									comptes_heberg.user_linux,
									comptes_heberg.offre,
									offre_heberg.id_offre,
									offre_heberg.espacedisk
									FROM commandes_data 
									LEFT JOIN comptes_heberg
									ON commandes_data.domaine_or_user_linux = comptes_heberg.user_linux
									LEFT JOIN offre_heberg
									ON comptes_heberg.offre = offre_heberg.id_offre
									WHERE commandes_data.type_commande = 1 
											AND commandes_data.type_produit = 0 
											AND commandes_data.commande_etat = 3
											AND server_apache = '".CURRENT_SERVER."'");
	While($commande = mysql_fetch_array($liste_commandes_)) {
		print_r($commande);
		// Création user, group, chmod home
		shell_exec("sudo useradd -s /bin/false -m -k ".CONFIG_ROOT."tpl/skel/ ".$commande['domaine_or_user_linux']);
		shell_exec("sudo chmod 750 -R /home/".$commande['domaine_or_user_linux']."/");
		shell_exec("sudo gpasswd -a www-data ".$commande['domaine_or_user_linux']);
		shell_exec("sudo chown ".$commande['domaine_or_user_linux'].":www-data /home/".$commande['domaine_or_user_linux']."/");
		
		if($commande['id_produit'] == 3) {
			$perso = mysql_fetch_array(query("SELECT * FROM offre_surmesure WHERE id_heberg = '".$commande['ch_id']."'"));
			$commande['espacedisk'] = $perso['espacedisk'];
		}

		// Quoat Soft+Hard
		$limit_soft = ($commande['espacedisk']-100)*1000;
		$limit_hard = $commande['espacedisk']*1000;
		shell_exec("sudo setquota -u ".$commande['domaine_or_user_linux']." $limit_soft $limit_hard 0 0 ".PARTITION);
		// Recup UID Linux
		$uid = explode('=', shell_exec("id ".$commande['domaine_or_user_linux']), 2);
		$uid = explode('(',$uid['1'],2);
		$uid = $uid['0'];
		
		// Changement état commande
		query("UPDATE commandes_data SET commande_etat = 2 WHERE id = '".$commande['co_id']."'");
		query("UPDATE comptes_heberg SET uid_linux = '".$uid."', etat = 1 WHERE id = '".$commande['ch_id']."'");
		query("UPDATE comptes_ftp SET uid = '".$uid."', gid = '".$uid."', actif = 1 WHERE userid = '".$commande['domaine_or_user_linux']."'");
	}
	
// ---------------------------------------------------------------------------------------------
//  Suppression des comptes d'hébergement
// HEBERGEMENT
// ---------------------------------------------------------------------------------------------
$liste_ = query("SELECT 
				comptes_heberg.*,
				UNIX_TIMESTAMP(comptes_heberg.expire)
				FROM comptes_heberg
				WHERE etat = '5' AND serveur_apache = '".CURRENT_SERVER."'");
While($liste = mysql_fetch_array($liste_)) {
	shell_exec("tar cf ".CONFIG_ROOT."tmp/".$liste['u_nic']."-".$liste['user_linux'].".tar /home/".$liste['user_linux']);
	$_ftp_co = ftp_connect("ns0.breizh-heberg.net");
	$_ftp_log = ftp_login($_ftp_co, "back", "KaflPmKVygEV65L");
	if(ftp_put($_ftp_co, "/olds/".$liste['u_nic']."-".$liste['user_linux'].".tar", CONFIG_ROOT."tmp/".$liste['u_nic']."-".$liste['user_linux'].".tar", FTP_BINARY)) {
		shell_exec("sudo userdel -r -f ".$liste['user_linux']);
		shell_exec("sudo groupdel ".$liste['user_linux']);
		query("UPDATE comptes_heberg SET etat = '51' WHERE id = '".$liste['id']."'");
	}
}

// ---------------------------------------------------------------------------------------------
// Changement d'offre
// HEBERGEMENT
// ---------------------------------------------------------------------------------------------
$liste_ = query("SELECT * FROM comptes_heberg WHERE etat = '43' AND serveur_apache = '".CURRENT_SERVER."'");
While($liste = mysql_fetch_array($liste_)) {
	$commande = mysql_fetch_array(query("SELECT 
												commandes_data.*,
												offre_heberg.espacedisk AS dsk,
												offre_heberg.id_offre
												FROM commandes_data 
												LEFT JOIN offre_heberg
												ON commandes_data.id_produit = offre_heberg.id_offre
												WHERE commandes_data.domaine_or_user_linux = '".$liste['user_linux']."' AND commandes_data.type_commande = 2 ORDER by commandes_data.id DESC"));
	$limit_soft = ($commande['dsk']-100)*1000;
	$limit_hard = $commande['dsk']*1000;
	shell_exec("sudo setquota -u ".$liste['user_linux']." $limit_soft $limit_hard $limit_soft $limit_hard ".PARTITION);
	query("UPDATE comptes_heberg SET etat = 1 WHERE id = '".$liste['id']."'");
}

// ---------------------------------------------------------------------------------------------
// Changement serveur [Apache][Ancien Serveur]
// HEBERGEMENT
// ---------------------------------------------------------------------------------------------
$_depl = query("SELECT 
					hebergactions_deplcompte.id AS depl_id,
					hebergactions_deplcompte.id_heberg,
					hebergactions_deplcompte.server_apache_n,
					hebergactions_deplcompte.server_mysql_n,
					hebergactions_deplcompte.etat,
					comptes_heberg.id,
					comptes_heberg.u_nic,
					comptes_heberg.uid_linux,
					comptes_heberg.user_linux,
					comptes_heberg.serveur_apache,
					comptes_heberg.etat,
					users.u_nic,
					users.u_email
					FROM hebergactions_deplcompte 
					LEFT JOIN comptes_heberg
					ON hebergactions_deplcompte.id_heberg = comptes_heberg.id		
					LEFT JOIN users
					ON comptes_heberg.u_nic = users.u_nic
					WHERE comptes_heberg.etat = 1
						AND hebergactions_deplcompte.etat = 1
						AND hebergactions_deplcompte.server_mysql_n = 0
						AND comptes_heberg.serveur_apache = ".CURRENT_SERVER);
While($depl = mysql_fetch_array($_depl)) {
	// mail Info
	$mail_content = array();
	$mail_content['{title}'] = "Apache - Votre compte d'hébergement est en cours de changement de serveur";
	$mail_content['{contenu}'] = "Bonjour,<br />
	Un administrateur a activé le changement de serveur Apache pour votre compte. Celui est actuellement en transfert. Un mail avec plus d'informations vous sera envoyé automatiquement à la fin du changement.";
	$mail = str_replace(array_keys($mail_content), array_values($mail_content), file_get_contents(CONFIG_ROOT."tpl/mail-default.html"));
	mail($depl['u_email'], '[Breizh Héberg] '.$mail_content['{title}'], $mail, $headers); 
	
	// Envoi des fichiers nouveau serveur
	@shell_exec("rm ".CONFIG_ROOT."tmp/".$depl['u_nic']."-".$depl['user_linux'].".tar");
	shell_exec("tar cf ".CONFIG_ROOT."tmp/".$depl['u_nic']."-".$depl['user_linux'].".tar /home/".$depl['user_linux']);
	$_ftp_co = ftp_connect("ns".$depl['server_apache_n'].".breizh-heberg.net");
	$_ftp_log = ftp_login($_ftp_co, "back", TMP_PASS);
	if(ftp_put($_ftp_co, "/depl/".$depl['u_nic']."-".$depl['user_linux'].".tar", CONFIG_ROOT."tmp/".$depl['u_nic']."-".$depl['user_linux'].".tar", FTP_BINARY)) {
		shell_exec("sudo userdel -r -f ".$depl['user_linux']);
		shell_exec("sudo groupdel ".$depl['user_linux']);
		query("UPDATE hebergactions_deplcompte SET etat = 3 WHERE id = '".$depl['depl_id']."'");
	}
}


// ---------------------------------------------------------------------------------------------
// Changement serveur [Apache][Nouveau Serveur]
// HEBERGEMENT
// ---------------------------------------------------------------------------------------------
$_depl = query("SELECT 
					hebergactions_deplcompte.id AS depl_id,
					hebergactions_deplcompte.id_heberg,
					hebergactions_deplcompte.server_apache_n,
					hebergactions_deplcompte.server_mysql_n,
					hebergactions_deplcompte.etat,
					comptes_heberg.id,
					comptes_heberg.u_nic,
					comptes_heberg.uid_linux,
					comptes_heberg.user_linux,
					comptes_heberg.serveur_apache,
					comptes_heberg.etat,
					comptes_heberg.offre,
					users.u_nic,
					users.u_email,
					offre_surmesure.id_heberg,
					offre_surmesure.espacedisk AS om_disk,
					offre_heberg.id_offre,
					offre_heberg.espacedisk AS o_disk
					FROM hebergactions_deplcompte 
					LEFT JOIN comptes_heberg
					ON hebergactions_deplcompte.id_heberg = comptes_heberg.id		
					LEFT JOIN users
					ON comptes_heberg.u_nic = users.u_nic
					LEFT JOIN offre_surmesure
					ON comptes_heberg.id = offre_surmesure.id_heberg
					LEFT JOIN offre_heberg
					ON comptes_heberg.offre = offre_heberg.id_offre	
					WHERE 	comptes_heberg.etat = 1
						AND hebergactions_deplcompte.etat = 3
						AND hebergactions_deplcompte.server_mysql_n = ''
						AND hebergactions_deplcompte.server_apache_n = '".CURRENT_SERVER."'");
While($depl = mysql_fetch_array($_depl)) {
	if(is_file(CONFIG_ROOT."tmp/depl/".$depl['u_nic']."-".$depl['user_linux'].".tar")) {
		shell_exec("sudo useradd -s /bin/false -m -k ".CONFIG_ROOT."tpl/skel/ ".$depl['user_linux']);
		shell_exec("sudo gpasswd -a www-data ".$depl['user_linux']);
		// Recup UID Linux
		$uid = explode('=', shell_exec("id ".$commande['domaine_or_user_linux']), 2);
		$uid = explode('(',$uid['1'],2);
		$uid = $uid['0'];
		// Installation fichiers
		shell_exec("cd / && sudo tar xvf ".CONFIG_ROOT."tmp/depl/".$depl['u_nic']."-".$depl['user_linux'].".tar");
		shell_exec("sudo chmod 750 -R /home/".$depl['user_linux']."/");
		shell_exec("sudo chown ".$depl['user_linux'].":www-data /home/".$depl['user_linux']."/");
		
		// Espace disk
		if($depl['offre'] == 3) {
			$depl['o_disk'] = $depl['om_disk'];
		}
		$limit_soft = ($depl['o_disk']-100)*1000;
		$limit_hard = $depl['o_disk']*1000;
		shell_exec("sudo setquota -u ".$depl['user_linux']." $limit_soft $limit_hard $limit_soft $limit_hard ".PARTITION);

		// Maj état
		query("UPDATE hebergactions_deplcompte SET etat = 4 WHERE id = '".$depl['depl_id']."'");
		
	}
	else { echo "No file ".CONFIG_ROOT."tmp/depl/".$depl['u_nic']."-".$depl['user_linux'].".tar"; }


}
	
deconnexionbdd();
shell_exec("sudo apache2ctl graceful");
?>
